from src.modules.knowbase.schemas.model_schema import FileResponse
from src.modules.knowbase.repository.entity.kb_file import File
from core.utils.paginator import Paginator
from core.dependencies import AsyncSessionLocal
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, delete, or_, asc
from core.decorators.database_decorator import with_async_session


class FileDao:
    @staticmethod
    @with_async_session()
    async def get_file_list(
        user_id: str = None,
        kb_id: str = None,
        keyword: str = None,
        page: int = 1,
        page_size: int = 10,
        session: AsyncSession = None,
    ) -> dict:

        query = select(File)
        if user_id:
            query = query.where(File.user_id == user_id)
        if kb_id:
            query = query.where(File.knowbase_id == kb_id)
        if keyword:
            query = query.where(
                or_(
                    File.file_name.ilike(f"%{keyword}%"),
                    File.file_path.ilike(f"%{keyword}%"),
                )
            )
        query = query.order_by(asc(File.uid))
        paginator = Paginator(
            session=session, model=File, response_model=FileResponse, base_query=query
        )
        return await paginator.paginate(page, page_size)

    @staticmethod
    async def delete_by_file_id(file_id: str):
        session: AsyncSession = AsyncSessionLocal()
        try:
            delete_sql = delete(File).where(File.file_id == file_id)
            result = await session.execute(delete_sql)
            await session.commit()
            return result.rowcount > 0
        except Exception as e:
            await session.rollback()  # 发生异常时回滚
            print(f"删除文件时出错: {e}")
            return False
        finally:
            await session.close()  # 确保会话关闭

    @staticmethod
    @with_async_session(auto_commit=False)
    async def upload_file(file_name: str, file_path: str, file_type: str, kb_id: str,session:AsyncSession =None):
        db_file = File(
            file_name=file_name,
            file_path=file_path,
            file_type=file_type,
            knowbase_id=kb_id,
        )
        session.add(db_file)
        await session.commit()
        await session.refresh(db_file)
        if db_file.uid is not None:
            return db_file
        else:
            return None
        
